package j.framework.base.controller;

import j.data.ActionResult;
import j.framework.base.service.ApplicationService;
import j.framework.core.*;
import j.util.DES;
import j.util.New;
import j.util.StringUtils;
import j.util.jdbc.JdbcTemplate;
import j.util.web.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 登录控制器
 * User: jason
 * Date: 2014/11/6 13:47
 */
@WebServlet(urlPatterns = "/login")
public class LoginController extends BaseController {
    @ApplicationBean
    private  JdbcTemplate jdbcTemplate;

    @ApplicationBean
    private ApplicationService applicationService;
    /**
     * 检测当前用户使用环境，能否使用本系统
     * 当用户环境为“windows操作环境”且浏览器为firefox时，才能使用本系统
     * @param view
     * @throws ServletException
     * @throws java.io.IOException
     */
    private void setCanLogin(HttpView view)throws ServletException,IOException{
        boolean canLogin = true;
        //todo 先放开浏览器限制，方便测试其它浏览器的兼容性
        /*String agentInfo = view.getRequest().getHeader("User-Agent");
        if(agentInfo.contains("Windows") && !agentInfo.contains("Firefox")){
            canLogin = false;
        }*/
        view.setAttribute("canLogin", canLogin);
    }

    @Override
    public void doDefaultGet(HttpView view) throws ServletException, IOException {
        setCanLogin(view);
        int port = view.getRequest().getServerPort();
        //便于本机调试
        if(port == 4900){
            view.setAttribute("userName", "admin");
            view.setAttribute("password", "123456");
        }
        view.forward("login");//=/WEB-INF/jsp/login.jsp
    }

    @Override
    public void doDefaultPost(HttpView view) throws ServletException, IOException {
        super.doDefaultPost(view);
    }

    /**
     * 验证用户
     * @param view
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    @WebRequest(action = "check",method = RequestMethod.POST)
    public void doCheckUser(HttpView view) throws ServletException,IOException{
        //1：接收页面传参
        String loginName = view.getParameter("userName");
        String password = view.getParameter("password");
        String rememberMe = view.getParameter("rememberme");
        //1.1判断页面是否有错误
        ActionResult ar = ActionResult.New();
        ar.isNotNull("loginName",loginName,"用户登录名是必须的.");
        ar.isNotNull("password", password, "用户密码是必须的");
        if(ar.hasErrors(view.getRequest())){
            setCanLogin(view);
            view.setAttribute("userName",loginName);
            view.forward("login");
//            return;
        }else{
            log.debug("验证用户的合法性");
            //1.2进行
            MemberStatus<IAuthorization> ms = FApplication.getMembershipProvider().validate(loginName, password, view.getRequest());  //这里的密码为明文
            SysLog log = SysLog.buildLog(null, "MOD20150319000000001", "系统登录", "系统登录", null, WebUtils.getRequestIP(view.getRequest()));
            if(ms.memberStatus == MemberStatus.OK){
                //验证成功
                //看看用户有没有选择了"记住我"选项,若选择了,则记入到cookie中
                if(StringUtils.isNotEmpty(rememberMe) && rememberMe.equals("rememberme")){
                    //用户选择了"记住我"选项
                    String userToken = DES.encrypt(String.format("%s~%s", loginName, password));
                    Cookie c1 = new Cookie("user_token_rememberme", userToken);
                    c1.setMaxAge(60*60*24*7);   //一周后过期

                    view.getResponse().addCookie(c1);
                }
                //将登录对象记录到session中
                WebUtils.setSessionAttribute(view.getRequest(), LoginUser.SESSION_KEY, ms.getMember());

                log.setLogContent("【登录成功】用户名 " + loginName);
                LoginUser loginUser = (LoginUser)ms.getMember();
                log.setOperateUserId(loginUser.getUserId());

                view.redirect("/user/center");
            }else{
                setCanLogin(view);
                view.setAttribute("userName", loginName);
                ar.add(ms.message);
                view.setAttribute(ActionResult.REQUEST_ITEMS_ATTRIBUTE_NAME, ar.toMap());
                log.setLogContent("【登录失败】用户名 " + loginName + " 密码 " + password + "ERROR " + ms.message);
                log.setOperateUserId(loginName);
                view.forward("login");
            }
            try {
                applicationService.log(log);
            }catch (Exception e){
                view.forward("login");
            }

        }

    }
    @WebRequest(action = "gd")
    public void doGetDataGridTestData(HttpView view) throws ServletException, IOException {
        List<Map<String,Object>> listMap = New.list();
        int total = view.getIntParamter("total", 200);
        Map<String,Object> map;
        //{ id: 'id' + i, name: '枯叶枯井可喖',age:333,scale:56.76,dsc:"sdfkskdffd" }
        for(int i=0;i<total;i++){
            map = New.map();
            map.put("id",i);
            map.put("name","枯叶枯井可喖"+i);
            map.put("age",333);
            map.put("scale",56.76);
            map.put("dsc","sdfkskdffd城标吴三桂自卫队");

            map.put("id1",i);
            map.put("name1","枯叶枯井可喖"+i);
            map.put("age1",333);
            map.put("scale1",56.76);
            map.put("dsc1","sdfkskdffd城标吴三桂自卫队");

            map.put("id2",i);
            map.put("name2","枯叶枯井可喖"+i);
            map.put("age2",333);
            map.put("scale2",56.76);
            map.put("dsc2","sdfkskdffd城标吴三桂自卫队");

            map.put("id3",i);
            map.put("name3","枯叶枯井可喖"+i);
            map.put("age3",333);
            map.put("scale3",56.76);
            map.put("dsc3","sdfkskdffd城标吴三桂自卫队");

            map.put("id4",i);
            map.put("name4","枯叶枯井可喖"+i);
            map.put("age4",333);
            map.put("scale4",56.76);
            map.put("dsc4","sdfkskdffd城标吴三桂自卫队");
            listMap.add(map);
        }
        view.toEasyUiGrid(total, listMap);
    }
    @WebRequest(action = "uby")
    public void doUpdateBaiduYun(HttpView view) throws ServletException,IOException{
        jdbcTemplate.execute("update test_baiduyun set receive_time=? where msg_id=?", new Date(), view.getParameter("msgId"));
    }
    @WebRequest(action = "tree")
    public void doTreeData(HttpView view) throws ServletException, IOException {
        HttpSession session = view.getRequest().getSession(false);
        session.setAttribute(LoginUser.SESSION_KEY, null);
        session.invalidate();
        view.redirect("/tree");
    }
}
